#!/bain/bash

Upgrade_Moodle()
{

    if  [ -s ${Default_Moodle_Dir}/moodle/config.php ]; then
        cd ${Default_Moodle_Dir}/moodle
        Old_Version=$( cat version.php | grep Human-friendly | awk -F"'" '{print $2}' )
     else
        echo -e "\033[31mError! Your Moodle Dir wrong, please check!\033[0m"
        exit 1
    fi
    echo "+---------------------------------------------------------"
    echo -e "  Current Moodle Version: \033[32m${Old_Version}\033[0m"
    echo "      You will upgrade Moodle to Latest release"
    echo "+---------------------------------------------------------"

    Press_Start

    Upgrade_status=$( sudo -u www git pull | grep Already )
    Stable_Version=$( sudo -u www git branch -a | sed '$d' | sed -n '$p' | awk -F "_" '{print $2}' )
    Current_Version=$( sudo -u www git branch -a | sed '$d' | grep '^*' |awk -F "_" '{print $2}' )
    if [ "$Upgrade_status" = "Already up-to-date." ] && [ "${Stable_Version}" = "${Current_Version}" ]; then
        echo -e "\033[32mYour Moodle is Latest release,not upgrade!\033[0m"
     else
        if [[ ${Stable_Version} -gt ${Current_Version} ]]; then
            sudo -u www git checkout -b MOODLE_${Stable_Version}_STABLE origin/MOODLE_${Stable_Version}_STABLE
            sudo -u www git pull
        fi
        sudo -u www /usr/bin/php admin/cli/maintenance.php --enable
        sudo -u www /usr/bin/php admin/cli/upgrade.php --non-interactive
        sudo -u www /usr/bin/php admin/cli/maintenance.php --disable
        New_Version=$( cat version.php | grep Human-friendly | awk -F"'" '{print $2}' )
        echo "Moodle $Old_Version Upgrade to $New_Version"
        Version_List=$( git branch -a | sed '$d' | grep '  MOODLE' |awk -F "_" '{print $2}' )
        for Version in ${Version_List}
        do
            sudo -u www git branch -D MOODLE_${Version}_STABLE
        done
        echo -e "\033[32m======== upgrade Moodle completed ======\033[0m"
    fi
    cd ${cur_dir}
}

